package com.srt.util.exception;

import cn.hutool.core.util.StrUtil;
import com.srt.util.Result;
import com.srt.util.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * controller层的异常处理
 *
 * @name: ExceptionConfigController
 * @author: rd07
 * @date: 2020/8/3
 * @time: 10:21
 */
@Slf4j
@ConditionalOnProperty(prefix = "controller", name = "handler", havingValue = "true")
@RestControllerAdvice
public class ExceptionConfigController {

    /**
     * 专门用来捕获和处理Controller层的PBusinessException异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(PBusinessException.class)
    public Result pBusinessExceptionHandler(PBusinessException e) {
        return ResultUtils.getFailure(e.getCode(), e.getMessageWithoutCode());
    }

    /**
     * 专门用来捕获和处理Controller层的MethodArgumentNotValidException异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result methodArgumentNotValidException(MethodArgumentNotValidException e) {
        if (e.getBindingResult().hasErrors()) {
            ObjectError error = e.getBindingResult().getAllErrors().get(0);
            String errorMessage = error.getDefaultMessage();
            if (StrUtil.isNotEmpty(errorMessage)) {
                String[] errorKeys = errorMessage.split(",");
                StringBuilder sb = new StringBuilder();
                for (String key : errorKeys) {
                    sb.append(PExceptionFactory.getMessage(key));
                }
                return ResultUtils.getFailure(errorMessage, sb.toString());
            } else {
                return ResultUtils.getFailure("-1", "前端参数校验失败");
            }
        }
        return ResultUtils.getFailure("-1", "前端参数校验失败");
    }

    /**
     * 专门用来捕获和处理Controller层的Exception异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public Result exception(Exception e) {
        log.error(e.getMessage(), e);
        return ResultUtils.getFailure("-1", e.getMessage());
    }
}
